package com.phpxiu.app.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.phpxiu.app.adapter.holder.CommonMsgViewHolder;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.MsgSender;
import com.phpxiu.app.model.msg.CommonMsg;
import com.phpxiu.app.model.msg.EnterMsg;
import com.phpxiu.app.model.msg.GoodMsg;
import com.phpxiu.app.model.msg.IMGiftMsg;
import com.phpxiu.app.model.msg.ManageMsg;
import com.phpxiu.app.model.msg.SystemMsg;
import com.phpxiu.app.model.response.SystemDefaultMsg;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.MsgTextView;
import com.phpxiu.app.view.dialog.LiveRoomAnimWin;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by WuJinZhou on 2016/5/14.
 */
public class CommonMsgListAdapter extends BaseAdapter implements View.OnClickListener {
    public final static String TAG="CommonMsgListAdapter";
    private int mLvSpanWidth;
    private int mLvSpanHeight;
    private LayoutInflater mInflater;
    private List<Object> msgList=new ArrayList<Object>();
    private static String noticePreFix;
    public final static String tempIconStr="lv_icon";
    private String likeMsg;
    private String noticeAdmin,noticeAdminCancel,noticeMute,noticeFollow;
    private String giftPrefix;
    private static ForegroundColorSpan urlLinkSpan=new ForegroundColorSpan(Color.parseColor("#ffFFFFFF"));
    private WeakReference<LiveRoomAnimWin>winRef;
    public CommonMsgListAdapter(Context context, List<Object> msgList) {
        likeMsg=context.getString(R.string.list_like_msg);
        giftPrefix=context.getString(R.string.list_gift_msg);
        noticePreFix=context.getString(R.string.list_notice_msg);
        noticeAdmin=context.getString(R.string.list_add_admin_msg);
        noticeAdminCancel=context.getString(R.string.list_remove_admin_msg);
        noticeMute=context.getString(R.string.list_mute_msg);
        noticeFollow=context.getString(R.string.list_follow_msg);
        mLvSpanWidth= KKYUtil.dip2px(context, 32.0f);
        mLvSpanHeight= KKYUtil.dip2px(context, 14f);
        mInflater=LayoutInflater.from(context);
        this.msgList = msgList;

    }

    @Override
    public int getCount() {
        return msgList.size();
    }

    @Override
    public Object getItem(int position) {
        return msgList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Object msg=null;
        try {
            msg=msgList.get(position);
        }catch (ArrayIndexOutOfBoundsException e){
            CrashReport.postCatchedException(e);
        }
        if(msg==null){
            return null;
        }
        CommonMsgViewHolder holder=null;
        if(convertView==null){
            convertView=mInflater.inflate(R.layout.common_msg_list_item_view,null);
            holder=new CommonMsgViewHolder(convertView);
            convertView.setTag(holder);
        }
        holder=(CommonMsgViewHolder)convertView.getTag();
        holder.msgContent.setBlank(false);
        holder.msgContent.setUid(null);
        holder.msgContent.setUrl(null);
        holder.msgContent.setOnClickListener(null);
        SpannableStringBuilder text=holder.text;
        text.clear();
        try {
            if (msg instanceof CommonMsg) {
                CommonMsg commonMsg = (CommonMsg) msg;
                int lvl=commonMsg.getFuser().getLvl();//主播等级
                String nick = commonMsg.getFuser().getNickname();
                String msgContent = commonMsg.getMsg();
                text.append(tempIconStr).append(" ").append(nick).append("：").append(msgContent);
                text.setSpan(KKYApp.getLvSpan(lvl, mLvSpanWidth, mLvSpanHeight), 0, tempIconStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.nickSpan, tempIconStr.length()+1, tempIconStr.length() + nick.length()+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.msgContent.setText(text);
                holder.msgContent.setBlank(true);
                holder.msgContent.setUid(commonMsg.getFuser().getUid());
                holder.msgContent.setOnClickListener(this);
            }
            if (msg instanceof IMGiftMsg) {
                IMGiftMsg giftMsg = (IMGiftMsg) msg;
                int lvl = giftMsg.getFuser().getLvl();//主播等级
                String nick = giftMsg.getFuser().getNickname();
                text.append(tempIconStr).append(" ").append(nick).append(" ").append(giftPrefix).append(giftMsg.getName());
                text.setSpan(KKYApp.getLvSpan(lvl, mLvSpanWidth, mLvSpanHeight), 0, tempIconStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.nickSpan, tempIconStr.length()+1, tempIconStr.length() + nick.length()+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.giftSpan, tempIconStr.length() + nick.length()+1, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.msgContent.setText(text);
                holder.msgContent.setBlank(true);
                holder.msgContent.setUid(giftMsg.getFuser().getUid());
                holder.msgContent.setOnClickListener(this);
            }
            if(msg instanceof GoodMsg){
                GoodMsg goodMsg=(GoodMsg)msg;
                int lvl = goodMsg.getFuser().getLvl();//主播等级
                String nick = goodMsg.getFuser().getNickname();
                text.append(tempIconStr).append(" ").append(nick).append(likeMsg);
                text.setSpan(KKYApp.getLvSpan(lvl, mLvSpanWidth, mLvSpanHeight), 0, tempIconStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.nickSpan, tempIconStr.length()+1, tempIconStr.length() + nick.length()+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //text.setSpan(KKYApp.HEART_SPAN_CACHE.get("heart_"+goodMsg.getStar()),text.length()-5,text.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.goodSpan,tempIconStr.length() + nick.length()+1,text.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.msgContent.setText(text);
                holder.msgContent.setBlank(true);
                holder.msgContent.setUid(goodMsg.getFuser().getUid());
                holder.msgContent.setOnClickListener(this);
            }
            if(msg instanceof ManageMsg){
                ManageMsg manageMsg=(ManageMsg)msg;
                String opera="";
                MsgSender msgSender =manageMsg.getTuser();
                MsgSender fUser=manageMsg.getFuser();
                try {
                    switch (manageMsg.getAction()){
                        case Constants.AV_IM_CMD_NOTICE_ADD_ADMIN:
                            opera= msgSender.getNickname()+noticeAdmin;
                            break;
                        case Constants.AV_IM_CMD_NOTICE_CANCEL_ADMIN:
                            opera= msgSender.getNickname()+noticeAdminCancel;
                            break;
                        case Constants.AV_IM_CMD_NOTICE_MUTE:
                            opera= msgSender.getNickname()+noticeMute;
                            break;
                        case Constants.AV_IM_CMD_NOTICE_ATTENTION:
                            opera=fUser.getNickname()+noticeFollow;
                            break;
                    }
                }catch (NullPointerException e){
                    e.printStackTrace();
                }
                text.append(noticePreFix).append("  ").append(opera);
                //text.setSpan(CommonMsgViewHolder.systemSpan, 0, noticePreFix.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //text.setSpan(CommonMsgViewHolder.systemSpan, noticePreFix.length(), text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.systemSpan,0,text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.msgContent.setText(text);
            }
            if(msg instanceof EnterMsg){
                //EnterMsg enterMsg=(EnterMsg)msg;
                //text.append(noticePreFix).append(enterMsg.getName()).append("进入了直播间");
                //text.setSpan(CommonMsgViewHolder.nickSpan, 0, noticePreFix.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //text.setSpan(CommonMsgViewHolder.systemSpan, noticePreFix.length(), text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //holder.msgContent.setText(text);
            }
            /**
             * 系统消息
             */
            if(msg instanceof SystemMsg){
                SystemMsg systemMsg=(SystemMsg)msg;
                String url=systemMsg.getUrl();
                text.append(noticePreFix).append(systemMsg.getMsg());
                if(url!=null&&url.startsWith("http")){
                    text.append(url);
                }
                //text.setSpan(CommonMsgViewHolder.nickSpan, 0, systemPreFix.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //text.setSpan(CommonMsgViewHolder.systemSpan, systemPreFix.length(), systemPreFix.length()+systemMsg.getMsg().length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.systemSpan, 0, text.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                if(url!=null&&url.startsWith("http")) {
                    text.setSpan(urlLinkSpan, noticePreFix.length() + systemMsg.getMsg().length(), text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.msgContent.setBlank(true);
                    holder.msgContent.setUrl(url);
                    holder.msgContent.setOnClickListener(this);
                }
                holder.msgContent.setText(text);
            }
            /**
             * 系统默认消息
             */
            if(msg instanceof SystemDefaultMsg){
                SystemDefaultMsg systemMsg=(SystemDefaultMsg)msg;
                KKYUtil.log("默认系统消息："+systemMsg.getContent());
                text.append(noticePreFix).append(systemMsg.getContent());
                //text.setSpan(CommonMsgViewHolder.nickSpan, 0, systemPreFix.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //text.setSpan(CommonMsgViewHolder.systemSpan, systemPreFix.length(), systemPreFix.length()+systemMsg.getContent().length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(CommonMsgViewHolder.systemSpan, 0, text.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.msgContent.setText(text);
            }
        }catch (NullPointerException e){
            KKYUtil.log("聊天列表项为空...");
            return null;
        }
        return convertView;
    }

    @Override
    public void onClick(View v) {
        if(v instanceof MsgTextView){
            MsgTextView view=(MsgTextView)v;
            if(view.isBlank()){
                if(view.getUid()!=null&&!"".equals(view.getUid())){
                    KKYUtil.log("弹出"+view.getUid()+"的卡片");
                    //TODO 弹出对应uid用户的卡片信息
                    if(winRef!=null&&winRef.get()!=null){
                        winRef.get().onShowUserWindow(view.getUid());
                    }
                }
                if(view.getUrl()!=null&&view.getUid().startsWith("http")){
                    //TODO 跳转到WebView预览连接内容
                    KKYUtil.log("跳转到WebView预览连接内容"+view.getUrl());
                    if(winRef!=null&&winRef.get()!=null){
                        winRef.get().goSystemWeb(noticePreFix,view.getUrl());
                    }
                }
            }
        }
    }

    public void setWin(LiveRoomAnimWin win){
        if(win==null){
            if(winRef!=null){
                winRef.clear();
                winRef=null;
            }
        }else{
            winRef=new WeakReference<LiveRoomAnimWin>(win);
        }
    }

    public static String toSBC1(String input) {
        char c[] = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == ' ') {
                c[i] = '\u3000';
            } else if (c[i] < '\177') {
                c[i] = (char) (c[i] + 65248);
            }
        }
        return new String(c);
    }
}
